#include "writer.h"
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstring>
#include <cerrno>
#include <atomic>
#include <chrono>
#include <thread>

int main()
{
    key_t key = ftok("netconf_mdfile/client_outfile.xml", 'a');
    TSNConfig tsnconfig;
    if (key == -1)
    {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    // 获取共享内存段的 ID
    int shmid = shmget(key, 0, 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    // 将共享内存段附加到进程地址空间
    Tunnel *tunnel = static_cast<Tunnel *>(shmat(shmid, nullptr, 0));
    if (tunnel == reinterpret_cast<Tunnel *>(-1))
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    // while (true)
    // {
        // 确保在访问共享内存之前，它已经被进程1正确初始化
        if (tunnel == nullptr)
        {
            std::cerr << "Shared memory not initialized\n";
            return 0;
        }

        // std::cout << "Tunnel ID: " << tunnel->mes << '\n';

        {
            // 使用原子操作检查 tag//更新--插入进OSS
            if (tunnel->tag.load(std::memory_order_acquire))
            {
                write_TSNConfig(&tsnconfig, tunnel);
                std::cout << "tsnconfig-device: " << tsnconfig.device_id << '\n';
                tunnel->tag.store(0, std::memory_order_acquire);
                            std::this_thread::sleep_for(std::chrono::seconds(1));
                 
            }


            // 写你的OSS代码
        }
    // }

    // 断开与共享内存段的连接
    if (shmdt(tunnel) == -1)
    {
        perror("shmdt");
        exit(EXIT_FAILURE);
    }

    return 0;
}